﻿using PMIS.WebApi.Model;
using Serilog;
using SqlSugar;
using StackExchange.Profiling;

namespace PMIS.WebApi.Extensions
{
    public static class SqlsugarSetup
    {
        public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration)
        {
            Action<SqlSugarClient> configAction = db =>
            {
                db.Aop.OnLogExecuting = (sql, parameters) =>
                {
                    var msg = "【SQL】\r\n" + UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, parameters) + "\r\n";
                    Log.Information(msg);
                    MiniProfiler.Current.CustomTiming("SQL", msg);
                };
                db.Aop.OnError = ex =>
                {
                    if (ex.Parametres == null) return;
                    var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
                    Log.Fatal("【SQL ERROR】\r\n" + pars + ex.Message + " \r\n");
                };
                db.Aop.OnLogExecuted = (sql, parameters) =>
                {
                    MiniProfiler.Current.CustomTiming("SQL",
                   $"【Sql耗时】:{Math.Round(db.Ado.SqlExecutionTime.TotalMilliseconds / 1000d, 4)}秒\r\n");
                };
            };

            DbType dbType = DbType.SqlServer;

            if (configuration.GetConnectionString("DbType") != null)
            {
                dbType = (DbType)Enum.Parse(typeof(DbType), configuration.GetConnectionString("DbType"));
            }

            var config = new ConnectionConfig()
            {
                ConfigId = "0",
                ConnectionString = configuration.GetConnectionString("DefaultConnection"),
                DbType = dbType,
                IsAutoCloseConnection = true,
            };

            SqlSugarScope sqlSugar = new SqlSugarScope(config, configAction);
            InitDatabase(sqlSugar);

            services.AddSingleton<ISqlSugarClient>(sqlSugar);
        }

        // 创建数据库和表
        private static void InitDatabase(SqlSugarScope sqlSugar)
        {
            sqlSugar.DbMaintenance.CreateDatabase();

            sqlSugar.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(Department));
            sqlSugar.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(Menu));
            sqlSugar.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(MenuAuthorize));
            sqlSugar.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(Role));
            sqlSugar.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(User));
            sqlSugar.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(DataDict));
            sqlSugar.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(Tenant));
        }
    }
}
